// import React, { useState, useEffect } from 'react';

import { Text, View, Image } from "@tarojs/components";
import { useEffect, useImperativeHandle, useState } from "react";
import { iconClock } from "../../../assets/files";
import './index.scss'

let intervalId;
const CountdownTimer = ({ initialSeconds, changeTime,ref }) => {
  const [seconds, setSeconds] = useState(initialSeconds);
  useImperativeHandle(ref, () => ({ // 暴露给父组件的方法
    clearIntervalFn,
    refreshInfo: () => {
    	console.log("子组件refreshInfo方法被调用")
    }
  }))

  useEffect(() => {
    changeTime(seconds)
  }, [seconds]);

  useEffect(() => {
    intervalId = setInterval(() => {
      setSeconds(seconds => seconds - 1);
      console.log(1);
    }, 1000);
    return () => clearInterval(intervalId);
  }, []);

  const clearIntervalFn = () => {
    // 清除定时器
    if (intervalId) {
      clearInterval(intervalId);
      intervalId = null;
    }
  };

  const formatTime = (time) => {
    const hours = Math.floor(time / 3600);
    const minutes = Math.floor((time % 3600) / 60);
    const secs = time % 60;
    return [hours, minutes, secs]
      .map(num => num < 10 ? '0' + num : num)
      .filter((num, i) => i > 0 || num !== '00')
      .join(':');
  };

  return (
    <View className="timeWrap">
      <Image className="iconClock" src={iconClock} />
      <Text>
        {seconds > 0 ? formatTime(seconds) : '00:00:00'}
      </Text>
    </View>
  );
};

export default CountdownTimer;